Find Largest Number Using Dynamic Memory Allocation with C++

04-11-17 Course- CPP

In this program, calloc() function is used to allocate the memory dynamically. Depending upon the number of elements, the required size is allocated which prevents the wastage of memory. If no memory is allocated, error is displayed and the program is terminated.

Source Code to Find Largest Element Using Dynamic Memory Allocation


#include <iostream>
#include <stdlib.h>
using namespace std;
int main(){
    int i,n;
    float *data;
    cout << "Enter total number of elements(1 to 100): ";
    cin >> n;
    data=(float*)calloc(n,sizeof(float));  /* Allocates the memory for 'n' elements */
    if(data==NULL)
    {
        cout << "Error!!! memory not allocated.";
        exit(0);
    }
    cout << endl;
    for(i=0;i<n;++i)  /* Stores number entered by user. */
    {
       cout << "Enter Number" << i+1 << ": ";
       cin >> data[i];
    }
    for(i=1;i<n;++i)  /* Loop to store largest number at address data */
    {
       if(*data<*(data+i)) /* Change < to > if you want to find smallest number */
           *data=*(data+i);
    }
    cout << "Largest element = " << *data;
    return 0;
}

Output


Enter total number of elements(1 to 100): 10

Enter Number 1: 2.34
Enter Number 2: 3.43
Enter Number 3: 6.78
Enter Number 4: 2.45
Enter Number 5: 7.64
Enter Number 6: 9.05
Enter Number 7: -3.45
Enter Number 8: -9.99
Enter Number 9: 5.67
Enter Number 10: 34.95
Largest element: 34.95